package com.idp.web.security.service;

import com.idp.app.dto.AppUserDto;
import com.idp.app.mapper.AppUserMapper;
import com.idp.common.enums.UserStatusEnum;
import com.idp.common.error.SystemException;
import com.idp.common.model.LoginInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * app用户验证处理
 * @author king
 */
@Service("AppUserDetailsServiceImpl")
public class AppUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(AppUserDetailsServiceImpl.class);

    @Autowired
    private AppUserMapper appUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AppUserDto appUser = appUserMapper.getUserByIdentity(username);

        if (appUser == null) {
            log.info("APP用户：{} 不存在.", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        if(appUser != null && UserStatusEnum.DISABLED.code.equals(appUser.getStatus())) {
            throw new SystemException("此账号被禁用");
        }

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId(appUser.getId());
        loginInfo.setAccount(appUser.getUname());
        loginInfo.setPwd(appUser.getPwd());
        loginInfo.setPhone(appUser.getPhone());
        loginInfo.setName(appUser.getNickname());

        return loginInfo;
    }

}
